package com.crm.system.service.impl.sendRoyaltyManager;

import com.crm.common.util.CommonUtils;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.messageprompt.MessagePrompt;
import com.crm.model.entity.sendRoyaltyManager.OrderSendRoyalty;
import com.crm.model.entity.sendRoyaltyManager.OrderSendRoyaltyLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.UserInfo;
import com.crm.model.vo.orderManager.CustomerProductOrderVO;
import com.crm.model.vo.user.UserInfoVO;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.messageprompt.MessagePromptDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.orderManager.CustomerProductOrderDetailDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.sendRoyaltyManager.SendRoyaltyDbService;
import com.crm.service.sendRoyaltyManager.SendRoyaltyLogDbService;
import com.crm.service.sys.UserInfoDbService;
import com.crm.system.service.sendRoyaltyManager.SendRoyaltyService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

/**
 * @Author: chaifuyou
 * @date 2021/4/7 14:24
 */
@Service
public class SendRoyaltyServiceImpl implements SendRoyaltyService {

    @Autowired
    private SendRoyaltyDbService sendRoyaltyDbService;

    @Autowired
    private CustomerProductOrderDbService customerProductOrderDbService;

    @Autowired
    private CustomerProductOrderDetailDbService customerProductOrderDetailDbService;

    @Autowired
    private CustomerContractDbService contractDbService;

    @Autowired
    private UserInfoDbService userInfoDbService;

    @Autowired
    private SendRoyaltyLogDbService sendRoyaltyLogDbService;

    @Autowired
    private MessagePromptDbService messagePromptDbService;

    @Autowired
    private FinishOrderDBservice finishOrderDBservice;

    /**
     * 录入提成
     * @param orderSendRoyalty
     */
    @Override
    @Transactional
    public void addSendRoyalty(OrderSendRoyalty orderSendRoyalty) {
        //訂單詳情
        CustomerProductOrderVO order = customerProductOrderDbService.getOrderInfoById(orderSendRoyalty.getProductOrderId());
        //合同详情
        CustomerContract customerContract = contractDbService.selectContractById(order.getContractId());
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        OrderSendRoyalty sendRoyalty=sendRoyaltyDbService.getSendRoyaltyInfo(orderSendRoyalty);
        if (Objects.nonNull(sendRoyalty)){
            orderSendRoyalty.setUpdatePeopleId(userAccount.getAccountId());
            orderSendRoyalty.setUpdateTm(new Date());
            sendRoyaltyDbService.delSendRoyalty(orderSendRoyalty);
            //提成发放修改日志
            OrderSendRoyaltyLog sendRoyaltyLog = new OrderSendRoyaltyLog();
            sendRoyaltyLog.setOrderSendRoyaltyLogId(CommonUtils.getGUID());
            sendRoyaltyLog.setProductOrderId(sendRoyalty.getProductOrderId());
            sendRoyaltyLog.setChsOrderSendRoyaltyId(sendRoyalty.getChsOrderSendRoyaltyId());
            sendRoyaltyLog.setFormerMoney(sendRoyalty.getRoyaltyMoney());
            sendRoyaltyLog.setNewMoney(orderSendRoyalty.getRoyaltyMoney());
            sendRoyaltyLog.setCreatePeopleId(userAccount.getAccountId());
            sendRoyaltyLog.setCreateTm(new Date());
            sendRoyaltyLogDbService.addSendRoyaltyLog(sendRoyaltyLog);
            addMessagePrompt(2,customerContract);
        }else {
            addMessagePrompt(1,customerContract);
        }
        orderSendRoyalty.setChsOrderSendRoyaltyId(CommonUtils.getGUID());
        orderSendRoyalty.setCreateTm(new Date());
        orderSendRoyalty.setCreatePeopleId(userAccount.getAccountId());
        orderSendRoyalty.setFinishOrderProductId(orderSendRoyalty.getFinishOrderProductId());
        sendRoyaltyDbService.addSendRoyalty(orderSendRoyalty);
        Integer sendRoyaltyNum=sendRoyaltyDbService.getSendRoyaltyNum(orderSendRoyalty.getProductOrderId(),null);
        //获取订单产品、活动总数
        Integer productNum=customerProductOrderDetailDbService.getOrderProductNum(orderSendRoyalty.getProductOrderId());
        if (Objects.nonNull(order)){
            if (Objects.isNull(order.getRoyaltyMoney())){
                BigDecimal newMoney=new BigDecimal("0.00");
                order.setRoyaltyMoney(newMoney);
            }
        }
        //加上新的提成金额减去原来的金额
        if (Objects.nonNull(sendRoyalty)){
            order.setRoyaltyMoney(order.getRoyaltyMoney().add(orderSendRoyalty.getRoyaltyMoney()).subtract(sendRoyalty.getRoyaltyMoney()));
        }else {
            order.setRoyaltyMoney(order.getRoyaltyMoney().add(orderSendRoyalty.getRoyaltyMoney()));
        }
        if (Objects.nonNull(productNum) && productNum == sendRoyaltyNum){
            order.setRoyaltyStatus("1");
        }else {
            order.setRoyaltyStatus("2");
        }
        //更新订单表
        customerProductOrderDbService.updateOrderComplete(order);
        if (Objects.nonNull(order)){
            CustomerContract contract=new CustomerContract();
            contract.setContractId(order.getContractId());
            contract.setCommissionStatus(order.getRoyaltyStatus());
            //更新合同
            contractDbService.updateCustomerContract(contract);
        }
        //维护tb_user_info
        UserInfoVO userInfVO = userInfoDbService.getUserInfoByAccountId(order.getCreatePeopleId());
        UserInfo userInfo=new UserInfo();
        userInfo.setUserId(userInfVO.getUserId());
        if (Objects.isNull(sendRoyalty)){ //录入
            if (Objects.nonNull(userInfVO.getRoyaltyCountMoney())){
                userInfo.setRoyaltyCountMoney(userInfVO.getRoyaltyCountMoney().add(orderSendRoyalty.getRoyaltyMoney()));
            }else if (Objects.isNull(userInfVO.getRoyaltyCountMoney())){
                userInfo.setRoyaltyCountMoney(orderSendRoyalty.getRoyaltyMoney());
            }
        }else {//修改提成
            userInfo.setRoyaltyCountMoney(userInfVO.getRoyaltyCountMoney().subtract(sendRoyalty.getRoyaltyMoney()).add(orderSendRoyalty.getRoyaltyMoney()));
        }
        userInfoDbService.updateUserInfoByUserId(userInfo);
        FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
        finishOrderProduct.setFinishOrderProductId(orderSendRoyalty.getFinishOrderProductId());
        finishOrderProduct.setGradeMoney(orderSendRoyalty.getScoreMoney());
        finishOrderProduct.setPerformanceConversionRatio(orderSendRoyalty.getScoreConvertRatio());
        finishOrderProduct.setRoyaltyMoney(orderSendRoyalty.getRoyaltyMoney());
        finishOrderProduct.setRoyaltyAccountId(userAccount.getAccountId());
        finishOrderProduct.setRoyaltyRecordTime(new Date());
        finishOrderProduct.setRoyaltyStatus("1");
        finishOrderProduct.setUpdatePeopleId(userAccount.getAccountId());
        finishOrderProduct.setUpdateTm(new Date());
        finishOrderDBservice.updateFinishOrderProduct(finishOrderProduct);

    }

    /**
     * 插入消息表
     * @param type 1录入提成 2修改提成
     * @param customerContract
     */
    public void addMessagePrompt(Integer type,CustomerContract customerContract){
        MessagePrompt messagePrompt = new MessagePrompt();
        if (Objects.nonNull(customerContract)){
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
            if (type == 1){
                messagePrompt.setMessageContent("您的合同编号："+customerContract.getContractNumber()+"提成金额已发放，请注意查收");
            }
            if (type == 2){
                messagePrompt.setMessageContent("您的合同编号："+customerContract.getContractNumber()+"提成金额已修改，请注意查收");
            }
            messagePrompt.setMessageId(CommonUtils.getGUID());
            messagePrompt.setMessageType(Short.valueOf("5"));
            messagePrompt.setRecipientAccountId(customerContract.getCreatePeopleId());
            messagePrompt.setCreatePeopleId(userAccount.getAccountId());
            messagePrompt.setCreateTm(new Date());
            messagePromptDbService.insertMessagePrompt(messagePrompt);
        }
    }

    /**
     * 获取最后一次发放的时间
     * @param orderId
     * @return
     */
    @Override
    public Date getMaxCreateTime(String orderId) {
        return sendRoyaltyDbService.getMaxCreateTime(orderId);
    }
}
